<script setup lang="ts">
import * as monaco from 'monaco-editor'
import {onMounted, ref, toRaw, watch} from "vue";

/**
 * 定义组件属性类型
 */
interface Props {
  value: string,
  language?: string
  handleChange: (v: string) => void
}

/**
 * 定义组件初始值
 */
const props = withDefaults(defineProps<Props>(), {
  value: () => '',
  language: 'java',
  handleChange: (v: string) => {
    console.log(v)
  }
})

const codeEditorRef = ref()
const codeEditor = ref()
const theme = ref('vs-dark')
onMounted(() => {
  if (!codeEditorRef.value){
    return
  }
  codeEditor.value = monaco.editor.create(codeEditorRef.value, {
    value: props.value,
    language: props.language,
    automaticLayout: true,
    theme: theme.value,
    minimap: {
      enabled: true
    },
    readOnly: false
  })
  // 编辑，监听内容的变化
  codeEditor.value.onDidChangeModelContent(() => {
   props.handleChange(toRaw(codeEditor.value).getValue())
  })
})

const fillValue = () => {
  if (!codeEditor.value){
    return
  }
  toRaw( codeEditor.value.setValue('填充值'))
}
watch([props.language], () => {
  codeEditor.value = monaco.editor.create(codeEditorRef.value, {
    value: props.value,
    language: props.language,
    automaticLayout: true,
    theme: theme.value,
    minimap: {
      enabled: true
    },
    readOnly: false
  })
})
onMounted(() => {
  if (!codeEditor.value){
    return
  }
})
</script>

<template>
  <div id="code-editor" ref="codeEditorRef" style="min-height: 400px">
  </div>
</template>

<style scoped lang="less">

</style>
